<template>
  <div class="game-container">
    <div class="game-header">
      <button 
        v-if="keySettings.showBackButton" 
        class="back-button" 
        @click="goBack" 
        tabindex="0" 
        ref="backButton"
      >
        返回
      </button>
      <h1 class="game-title">猜谜语</h1>
    </div>
    
    <div class="game-content">
      <div class="riddle-layout">
        <div class="riddle-card">
          <h2 class="riddle-question">{{ currentRiddle.question }}</h2>
          <div class="riddle-hint" v-if="showHint">提示: {{ currentRiddle.hint }}</div>
          
          <div class="options-container">
            <button 
              v-for="(option, index) in currentRiddle.options" 
              :key="index"
              class="option-button"
              :class="{ 
                'selected': selectedOption === index,
                'correct': showResult && selectedOption === index && index === currentRiddle.correctIndex,
                'incorrect': showResult && selectedOption === index && index !== currentRiddle.correctIndex
              }"
              @click="selectOption(index)"
              tabindex="0"
              ref="optionButtons"
            >
              {{ option }}
            </button>
          </div>
          
          <div class="controls">
            <button 
              class="control-button hint-button" 
              @click="toggleHint"
              tabindex="0"
              ref="hintButton"
            >
              {{ showHint ? '隐藏提示' : '显示提示' }}
            </button>
            
            <button 
              class="control-button next-button" 
              @click="nextRiddle"
              tabindex="0"
              ref="nextButton"
            >
              {{ showResult ? '下一题' : '确认' }}
            </button>
          </div>
          
          <div class="result-message" :class="{ 'visible': showResult }">
            <div v-if="isCorrect" class="correct-message">回答正确!</div>
            <div v-else class="incorrect-message">
              回答错误! 正确答案是: {{ currentRiddle.options[currentRiddle.correctIndex] }}
            </div>
          </div>
        </div>

        <div class="timer-sidebar">
          <div class="timer-display">
            <div class="timer-label">倒计时</div>
            <div class="timer-value" :class="{ 'warning': timeLeft <= 10, 'danger': timeLeft <= 5 }">
              {{ timeLeft }}秒
            </div>
            <div class="timer-progress">
              <div class="progress-bar" :style="{ width: (timeLeft / 30) * 100 + '%' }"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router';
import { getKeySettings, setupGlobalKeyHandlers, type KeySettings } from '../utils/keySettings';

const router = useRouter();
const backButton = ref<HTMLElement | null>(null);
const hintButton = ref<HTMLElement | null>(null);
const nextButton = ref<HTMLElement | null>(null);
const optionButtons = ref<HTMLElement[]>([]);

// 按键设置
const keySettings = reactive<KeySettings>({
  showBackButton: true,
  enableEscapeKey: true,
  enableContextMenu: true,
  enableKeyboardNavigation: true
});

// 倒计时相关
const timeLeft = ref(30);
const timer = ref<number | null>(null);
const isTimerRunning = ref(false);

// 谜语数据
const riddles = [
  {
    question: "一个人搬起石头砸自己的脚（打一成语）",
    hint: "自己做了对自己不利的事",
    options: ["搬起石头砸自己的脚", "自作自受", "搬石砸脚", "自食其果"],
    correctIndex: 1
  },
  {
    question: "一人得道，鸡犬升天（打一成语）",
    hint: "比喻一个人做了官，他的亲友也跟着得势",
    options: ["一人得道", "鸡犬升天", "一人得道，鸡犬升天", "飞黄腾达"],
    correctIndex: 1
  },
  {
    question: "八仙过海（打一成语）",
    hint: "比喻各自用不同的方法或本领做事",
    options: ["八仙过海", "各显神通", "各有所长", "各尽所能"],
    correctIndex: 1
  },
  {
    question: "小葱拌豆腐（打一成语）",
    hint: "形容事物洁白",
    options: ["清清白白", "洁白如雪", "白璧无瑕", "明明白白"],
    correctIndex: 0
  },
  {
    question: "一个西瓜两头切（打一字）",
    hint: "西瓜两头的字母",
    options: ["合", "分", "瓜", "西"],
    correctIndex: 2
  }
];

const currentRiddleIndex = ref(0);
const currentRiddle = ref(riddles[0]);
const selectedOption = ref(-1);
const showHint = ref(false);
const showResult = ref(false);
const isCorrect = ref(false);

// 启动倒计时
const startTimer = () => {
  if (timer.value) {
    clearInterval(timer.value);
  }
  
  timeLeft.value = 30;
  isTimerRunning.value = true;
  
  timer.value = setInterval(() => {
    if (timeLeft.value > 0) {
      timeLeft.value--;
    } else {
      // 时间到，自动显示结果
      if (!showResult.value) {
        showResult.value = true;
        isCorrect.value = false;
        isTimerRunning.value = false;
      }
    }
  }, 1000) as unknown as number;
};

// 停止倒计时
const stopTimer = () => {
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
  isTimerRunning.value = false;
};

// 返回主页
const goBack = () => {
  router.push('/');
};

// 选择选项
const selectOption = (index: number) => {
  if (!showResult.value) {
    selectedOption.value = index;
  }
};

// 切换提示显示
const toggleHint = () => {
  showHint.value = !showHint.value;
};

// 下一题或确认答案
const nextRiddle = () => {
  if (showResult.value) {
    // 进入下一题
    currentRiddleIndex.value = (currentRiddleIndex.value + 1) % riddles.length;
    currentRiddle.value = riddles[currentRiddleIndex.value];
    selectedOption.value = -1;
    showHint.value = false;
    showResult.value = false;
    // 重新开始倒计时
    startTimer();
  } else if (selectedOption.value !== -1) {
    // 显示结果
    isCorrect.value = selectedOption.value === currentRiddle.value.correctIndex;
    showResult.value = true;
    // 停止倒计时
    stopTimer();
  }
};

// 键盘导航处理
const handleKeyDown = (event: KeyboardEvent) => {
  switch (event.key) {
    case 'ArrowUp':
      navigateFocus('up');
      break;
    case 'ArrowDown':
      navigateFocus('down');
      break;
    case 'ArrowLeft':
      navigateFocus('left');
      break;
    case 'ArrowRight':
      navigateFocus('right');
      break;
    case 'Enter':
      if (document.activeElement === backButton.value) {
        goBack();
      } else if (document.activeElement === hintButton.value) {
        toggleHint();
      } else if (document.activeElement === nextButton.value) {
        nextRiddle();
      } else {
        // 检查是否是选项按钮
        const optionIndex = optionButtons.value.findIndex(btn => btn === document.activeElement);
        if (optionIndex !== -1) {
          selectOption(optionIndex);
        }
      }
      break;
  }
};

// 焦点导航
const navigateFocus = (direction: 'up' | 'down' | 'left' | 'right') => {
  // 这里实现基于当前焦点元素的导航逻辑
  // 简化版本，实际应用中可能需要更复杂的导航逻辑
  const activeElement = document.activeElement;
  
  if (activeElement === backButton.value) {
    if (direction === 'down') {
      optionButtons.value[0]?.focus();
    }
  } else if (optionButtons.value.includes(activeElement as HTMLElement)) {
    const currentIndex = optionButtons.value.findIndex(btn => btn === activeElement);
    if (direction === 'up' && currentIndex < 2) {
      backButton.value?.focus();
    } else if (direction === 'down' && currentIndex >= 2) {
      hintButton.value?.focus();
    } else if (direction === 'left' && currentIndex % 2 === 1) {
      optionButtons.value[currentIndex - 1]?.focus();
    } else if (direction === 'right' && currentIndex % 2 === 0 && currentIndex < optionButtons.value.length - 1) {
      optionButtons.value[currentIndex + 1]?.focus();
    }
  } else if (activeElement === hintButton.value) {
    if (direction === 'up') {
      optionButtons.value[2]?.focus();
    } else if (direction === 'right') {
      nextButton.value?.focus();
    }
  } else if (activeElement === nextButton.value) {
    if (direction === 'up') {
      optionButtons.value[3]?.focus();
    } else if (direction === 'left') {
      hintButton.value?.focus();
    }
  }
};

// 加载按键设置的函数
const loadKeySettings = async () => {
  const settings = await getKeySettings();
  Object.assign(keySettings, settings);
};

// 页面获得焦点时重新加载设置
const handleVisibilityChange = () => {
  if (!document.hidden) {
    loadKeySettings();
  }
};

onMounted(async () => {
  // 初始加载按键设置
  await loadKeySettings();
  
  // 设置全局按键处理器
  const cleanup = setupGlobalKeyHandlers(keySettings, {
    onEscape: () => goBack(),
    onKeyDown: keySettings.enableKeyboardNavigation ? handleKeyDown : undefined
  });
  
  // 监听页面可见性变化，当页面重新获得焦点时重新加载设置
  document.addEventListener('visibilitychange', handleVisibilityChange);
  
  // 初始聚焦到返回按钮（如果显示的话）
  if (keySettings.showBackButton) {
    backButton.value?.focus();
  }
  
  // 开始倒计时
  startTimer();
  
  // 组件卸载时清理
  onBeforeUnmount(() => {
    cleanup();
    document.removeEventListener('visibilitychange', handleVisibilityChange);
    // 清除倒计时
    stopTimer();
  });
});
</script>

<style scoped>
.game-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  padding: 2rem;
  background-color: #121212;
  color: white;
}

.game-header {
  display: flex;
  align-items: center;
  margin-bottom: 2rem;
  position: relative;
}

.back-button {
  position: absolute;
  left: 0;
  padding: 0.75rem 1.5rem;
  background-color: #333;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1.2rem;
  transition: background-color 0.3s;
}

.back-button:hover, .back-button:focus {
  background-color: #555;
  outline: 3px solid #4a90e2;
}

.game-title {
  width: 100%;
  text-align: center;
  font-size: 2.5rem;
  margin: 0;
}

.game-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex-grow: 1;
}

.riddle-layout {
  display: flex;
  gap: 1.5rem;
  width: 100%;
  max-width: 1400px;
  align-items: flex-start;
}

.riddle-card {
  background-color: #2a2a2a;
  border-radius: 16px;
  padding: 2rem;
  flex: 1;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(74, 144, 226, 0.1);
  transition: all 0.3s ease;
  
  &:hover {
    border-color: rgba(74, 144, 226, 0.3);
    box-shadow: 0 15px 30px rgba(0, 0, 0, 0.4);
  }
}

.timer-sidebar {
  width: 280px;
  min-width: 280px;
  background-color: #2a2a2a;
  border-radius: 16px;
  padding: 1.5rem;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  height: fit-content;
}

.timer-display {
  text-align: center;
  width: 100%;
}

.timer-label {
  font-size: 1.2rem;
  color: #aaa;
  margin-bottom: 1rem;
}

.timer-value {
  font-size: 3rem;
  font-weight: bold;
  color: #4a90e2;
  margin-bottom: 1.5rem;
  transition: color 0.3s ease;
  text-shadow: 0 0 10px rgba(74, 144, 226, 0.3);
}

.timer-value.warning {
  color: #f39c12;
  animation: pulse 1s infinite;
  text-shadow: 0 0 10px rgba(243, 156, 18, 0.5);
}

.timer-value.danger {
  color: #e74c3c;
  animation: pulse 0.5s infinite;
  text-shadow: 0 0 10px rgba(231, 76, 60, 0.5);
}

.timer-progress {
  width: 100%;
  height: 8px;
  background-color: #444;
  border-radius: 4px;
  overflow: hidden;
}

.progress-bar {
  height: 100%;
  background: linear-gradient(90deg, #e74c3c 0%, #f39c12 50%, #4a90e2 100%);
  transition: width 1s linear;
  border-radius: 4px;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}

.riddle-question {
  font-size: 2rem;
  margin-bottom: 2rem;
  text-align: center;
}

.riddle-hint {
  background-color: #3a3a3a;
  padding: 1rem;
  border-radius: 8px;
  margin-bottom: 2rem;
  text-align: center;
  font-style: italic;
}

.options-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.option-button {
  padding: 1.5rem;
  background-color: #333;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1.2rem;
  transition: all 0.3s;
  text-align: center;
}

.option-button:hover, .option-button:focus {
  background-color: #444;
  transform: translateY(-5px);
  outline: 3px solid #4a90e2;
}

.option-button.selected {
  background-color: #4a90e2;
}

.option-button.correct {
  background-color: #4caf50;
}

.option-button.incorrect {
  background-color: #f44336;
}

.controls {
  display: flex;
  justify-content: space-between;
  margin-top: 2rem;
}

.control-button {
  padding: 1rem 2rem;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1.2rem;
  transition: background-color 0.3s;
}

.hint-button {
  background-color: #555;
  color: white;
}

.hint-button:hover, .hint-button:focus {
  background-color: #666;
  outline: 3px solid #4a90e2;
}

.next-button {
  background-color: #4a90e2;
  color: white;
}

.next-button:hover, .next-button:focus {
  background-color: #3a80d2;
  outline: 3px solid #4a90e2;
}

.result-message {
  margin-top: 2rem;
  padding: 1.5rem;
  border-radius: 8px;
  text-align: center;
  font-size: 1.5rem;
  background-color: rgba(42, 42, 42, 0);
  box-shadow: none;
  transition: all 0.3s ease;
  opacity: 0;
  visibility: hidden;
  height: 0;
  padding: 0;
}

.result-message.visible {
  background-color: rgba(42, 42, 42, 0.9);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
  opacity: 1;
  visibility: visible;
  height: auto;
  padding: 1.5rem;
}

.correct-message {
  background-color: rgba(76, 175, 80, 0.2);
  color: #4caf50;
  padding: 1rem;
  border-radius: 4px;
}

.incorrect-message {
  background-color: rgba(244, 67, 54, 0.2);
  color: #f44336;
  padding: 1rem;
  border-radius: 4px;
}

/* 滚动条样式 */
.result-message::-webkit-scrollbar {
  width: 8px;
}

.result-message::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

.result-message::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 4px;
}

.result-message::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}

/* 响应式布局 */
/* 小屏幕适配 */
@media (max-height: 700px) {
  .game-container {
    padding: clamp(0.5rem, 2vw, 1.5rem);
  }
  
  .game-title {
    font-size: clamp(1.5rem, 4vw, 2rem);
  }
  
  .riddle-card {
    padding: clamp(1rem, 3vw, 1.5rem);
  }
  
  .riddle-question {
    font-size: clamp(1.3rem, 3vw, 1.8rem);
    margin-bottom: 1.5rem;
  }
  
  .option-button {
    padding: clamp(0.8rem, 2vw, 1.2rem);
    font-size: clamp(1rem, 2.5vw, 1.1rem);
  }
  
  .control-button {
    padding: clamp(0.8rem, 2vw, 1rem) clamp(1rem, 3vw, 1.5rem);
    font-size: clamp(1rem, 2.5vw, 1.1rem);
  }
}

@media (max-width: 768px) {
  .game-container {
    padding: clamp(0.5rem, 3vw, 1rem);
  }
  
  .game-header {
    margin-bottom: 1rem;
  }
  
  .back-button {
    padding: clamp(0.5rem, 2vw, 0.75rem) clamp(0.8rem, 3vw, 1.2rem);
    font-size: clamp(0.9rem, 3vw, 1.1rem);
  }
  
  .game-title {
    font-size: clamp(1.5rem, 5vw, 2rem);
  }
  
  .riddle-layout {
    flex-direction: row;
    gap: 1rem;
    align-items: flex-start;
  }
  
  .riddle-card {
    padding: clamp(1rem, 4vw, 1.5rem);
    flex: 1;
  }
  
  .timer-sidebar {
    width: 200px;
    padding: 1rem;
    flex-shrink: 0;
  }
  
  .timer-value {
    font-size: 2rem;
  }
  
  .riddle-question {
    font-size: clamp(1.2rem, 4vw, 1.6rem);
  }
  
  .options-container {
    grid-template-columns: 1fr;
    gap: 1rem;
  }
  
  .controls {
    flex-direction: column;
    gap: 1rem;
  }
  
  .result-message {
    font-size: clamp(1rem, 3vw, 1.3rem);
  }
}

@media (max-width: 480px) {
  .riddle-layout {
    flex-direction: column;
    gap: 1rem;
  }
  
  .timer-sidebar {
    width: 100%;
    order: -1;
    padding: 1rem;
  }
  
  .timer-value {
    font-size: 2.5rem;
  }
  
  .riddle-card {
    padding: 1.5rem;
  }
  
  .riddle-hint {
    padding: clamp(0.8rem, 3vw, 1rem);
    margin-bottom: 1.5rem;
    font-size: clamp(0.9rem, 3vw, 1.1rem);
  }
  
  .option-button {
    padding: clamp(1rem, 4vw, 1.2rem);
    font-size: clamp(1rem, 3vw, 1.1rem);
  }
  
  .control-button {
    width: 100%;
    margin: 0.25rem 0;
  }
}

/* 高度受限屏幕适配 */
@media (max-height: 600px) {
  .game-header {
    margin-bottom: 1rem;
  }
  
  .riddle-question {
    margin-bottom: 1rem;
  }
  
  .riddle-hint {
    margin-bottom: 1rem;
  }
  
  .options-container {
    margin-bottom: 1rem;
  }
}

/* 中等屏幕适配 */
@media (min-width: 769px) and (max-width: 1199px) {
  .timer-sidebar {
    width: 250px;
    padding: 1.5rem;
  }
  
  .timer-value {
    font-size: 2.5rem;
  }
}

/* 大屏幕适配 */
@media (min-width: 1200px) {
  .riddle-layout {
    max-width: 1400px;
    margin: 0 auto;
  }
  
  .timer-sidebar {
    width: 320px;
  }
}

/* 适配电视屏幕 */
@media (min-width: 1920px) {
  .game-title {
    font-size: 3rem;
  }
  
  .riddle-question {
    font-size: 2.5rem;
  }
  
  .option-button, .control-button {
    font-size: 1.5rem;
    padding: 1.5rem 2.5rem;
  }
  
  .timer-value {
    font-size: 4rem;
  }
  
  .timer-label {
    font-size: 1.5rem;
  }
}
</style>